package ivansalvadori.diariopushweb.view.security;

import ivansalvadori.diariopushweb.model.Usuario;
import ivansalvadori.diariopushweb.service.UsuarioService;
import ivansalvadori.diariopushweb.view.usuario.insert.InserirUsuario;

import javax.xml.bind.ValidationException;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

@SuppressWarnings("serial")
public class LoginPage extends WebPage {

	@SpringBean
	private UsuarioService usuarioService;

	private String email;
	private String password;

	public LoginPage() {

		add(new FeedbackPanel("feedback"));

		add(new LoginForm(new Usuario()));

		Link<InserirUsuario> link = new Link<InserirUsuario>(
				"linkCadastro") {
			@Override
			public void onClick() {
				setResponsePage(InserirUsuario.class);
			}
		};

		add(link);

	}

	public class LoginForm extends Form<Usuario> {

		public LoginForm(Usuario usuario) {
			super("usuarioForm");
			IModel<Usuario> model = new CompoundPropertyModel<Usuario>(usuario);
			this.setModel(model);

			RequiredTextField<String> campoEmail = new RequiredTextField<String>(
					"email");
			add(campoEmail);

			PasswordTextField camposenha = new PasswordTextField("senha");
			add(camposenha);

		}

		@Override
		public final void onSubmit() {
			email = this.getModelObject().getEmail();
			password = this.getModelObject().getSenha();
			login();
		}

	}

	private void login() {

		try {
			Usuario usuario = usuarioService.login(email, password);

			MySession session = (MySession) getSession();
			session.setUsuario(usuario);
			if (!continueToOriginalDestination()) {
				setResponsePage(getApplication().getHomePage());
			}

		} catch (ValidationException e) {
			error(e.getMessage());

		}

	}

}
